<template>
  <t-drawer
    :visible="visible"
    :header="drawerTitle"
		:footer="drawerFooter"
		size="50%"
    placement="right"
    @close="handleClose"
  >
    <!-- 抽屉内容区域 -->
    <div class="content-drawer-body">
      <t-form
        ref="contentForm"
        :data="formData"
        :rules="formRules"
        label-align="right"
        label-width="120px"
        class="content-form"
      >
        <!-- 名称 -->
        <t-form-item label="名称" name="name">
          <t-input
            v-model="formData.name"
            placeholder="请输入名称"
            maxlength="100"
          />
        </t-form-item>

        <!-- 作者 -->
        <t-form-item label="作者" name="author">
          <t-input
            v-model="formData.author"
            placeholder="请输入作者姓名"
            maxlength="50"
          />
        </t-form-item>

        <!-- 图片上传 -->
        <t-form-item label="图片内容" name="banner">
          <div style="display: flex; flex-direction: column; width: 100%;">
						<!-- 文件上传 -->
						<t-upload
							:action="uploadAction"
							:accept="'image/*'"
							:size-limit="{ size: 10, unit: 'MB' }"
							:format-response="formatImageResponse"
							:on-success="handleImageSuccess"
							:on-fail="handleUploadFail"
							@waiting-upload-files-change="handleImageProgress"
							:draggable="true"
							:show-upload-list="false"
							:auto-upload="true"
							:disabled="imageUploading"
							theme="custom"
							tips="支持拖拽上传，单个文件不超过10MB，最多上传10张图片"
							style="width: 100%; margin-bottom: 8px;"
						>
							<template #drag-content>
								<div v-loading="imageUploading" class="upload-drag-content">
									<template>
										<t-icon name="cloud-upload" size="36px" />
										<div class="upload-text">
											<p>点击上传图片或将图片拖拽到此区域</p>
											<p class="upload-tips">支持 JPG、PNG、GIF 格式，单个文件不超过10MB</p>
										</div>
									</template>
								</div>
							</template>
						</t-upload>

          <!-- 文件列表 -->
          <div v-if="formData.banner.length > 0">
            <div class="file-list-header">
              <span class="file-count">已上传图片：{{ formData.banner.length }} 个</span>
            </div>
            <div class="file-list-container">
              <div
                v-for="(url, index) in formData.banner"
                :key="index"
                class="file-item"
              >
                <div class="file-preview" @click="previewImage(url, index)">
                  <img :src="url" :alt="`图片${index + 1}`" class="preview-thumbnail" />
                </div>
                <div class="file-info">
                  <t-icon name="image" class="file-icon" />
                  <span class="file-name">{{ getFileName(url) }}</span>
                </div>
                <div class="file-actions">
                  <t-button
                    theme="primary"
                    variant="text"
                    size="small"
                    @click="previewImage(url, index)"
                    title="预览"
                  >
                    <t-icon name="play-circle" />
                  </t-button>
                  <t-button
                    theme="danger"
                    variant="text"
                    size="small"
                    @click="removeFile('banner', index)"
                    title="删除"
                  >
                    <t-icon name="delete" />
                  </t-button>
                </div>
              </div>
            </div>
          </div>
					</div>
        </t-form-item>

        <!-- 视频上传 -->
        <t-form-item label="视频内容" name="video">
          <div style="display: flex; flex-direction: column; width: 100%;">
						<!-- 文件上传 -->
						<t-upload
            :action="uploadAction"
            :accept="'video/*'"
            :size-limit="{ size: 100, unit: 'MB' }"
            :format-response="formatVideoResponse"
            :on-success="handleVideoSuccess"
            :on-fail="handleUploadFail"
            @waiting-upload-files-change="handleVideoProgress"
            :draggable="true"
            :show-upload-list="false"
            :auto-upload="true"
            :disabled="videoUploading"
            theme="custom"
            tips="支持拖拽上传，单个文件不超过100MB，最多上传5个视频"
            style="width: 100%; margin-bottom: 8px;"
          >
            <template #drag-content>
              <div v-loading="videoUploading" class="upload-drag-content">
                <template>
                  <t-icon name="video" size="36px" />
                  <div class="upload-text">
                    <p>点击上传视频或将视频拖拽到此区域</p>
                    <p class="upload-tips">支持 MP4、AVI、MOV 格式，单个文件不超过100MB</p>
                  </div>
                </template>
              </div>
            </template>
          </t-upload>

          <!-- 文件列表 -->
          <div v-if="formData.video.length > 0">
            <div class="file-list-header">
              <span class="file-count">已上传视频：{{ formData.video.length }} 个</span>
            </div>
            <div class="file-list-container">
              <div
                v-for="(url, index) in formData.video"
                :key="index"
                class="file-item"
              >
                <div class="file-preview" @click="playVideo(url)">
                  <div class="video-thumbnail">
                    <t-icon name="video" size="24px" />
                    <span class="play-icon">▶</span>
                  </div>
                </div>
                <div class="file-info">
                  <t-icon name="video" class="file-icon" />
                  <span class="file-name">{{ getFileName(url) }}</span>
                </div>
                <div class="file-actions">
                  <t-button
                    theme="primary"
                    variant="text"
                    size="small"
                    @click="playVideo(url)"
                    title="播放"
                  >
                    <t-icon name="play-circle" />
                  </t-button>
                  <t-button
                    theme="danger"
                    variant="text"
                    size="small"
                    @click="removeFile('video', index)"
                    title="删除"
                  >
                    <t-icon name="delete" />
                  </t-button>
                </div>
              </div>
            </div>
          </div>
					</div>
        </t-form-item>

        <!-- 富文本编辑器 -->
        <t-form-item v-if="visible" label="文本内容" name="rawHtml">
          <div class="rich-editor-wrapper">
            <Toolbar
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: calc(100vh - 300px)"
              v-model="formData.rawHtml"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </t-form-item>
      </t-form>
    </div>
  </t-drawer>
</template>

<script>
// 引入富文本编辑器
import Vue from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { DialogPlugin as TDialog } from 'tdesign-vue';
// 引入接口
import { getArticleByContentCode, createCatalogContent, updateCatalogContent } from '@/api/catalog';

export default Vue.extend({
  name: 'ContentDrawer',
  components: { Editor, Toolbar },
  model: {
    prop: 'visible',
    event: 'update:visible',
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    nodeData: {
      type: Object,
      default: () => ({}),
    },
    // categoryId需要从父组件透传
    categoryId: {
      type: [String, Number],
      default: '',
    },
  },
  emits: ['update:visible', 'success'],
  data() {
    return {
      editor: null,
      formData: {
        id: null,
        name: '',
        author: '',
        banner: [],
        video: [],
        rawHtml: '<p>请输入文本内容...</p>',
      },
      formRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 50, message: '名称不能超过50个字符', trigger: 'blur' },
        ],
        author: [
          { required: true, message: '请输入作者姓名', trigger: 'blur' },
          { max: 50, message: '作者姓名不能超过50个字符', trigger: 'blur' },
        ],
        rawHtml: [
          { required: true, message: '请输入文本内容', trigger: 'blur' },
        ],
      },
      uploadAction: '/api/cms/tools/upload', // 上传接口地址，需要根据实际情况修改
      // 富文本编辑器配置
      toolbarConfig: {
        toolbarKeys: [
          'headerSelect',
          '|',
          'bold',
          'italic',
          'underline',
          'through',
          'code',
          'sup',
          'sub',
          'clearStyle',
          '|',
          'color',
          'bgColor',
          '|',
          'fontSize',
          'fontFamily',
          'lineHeight',
          '|',
          'bulletedList',
          'numberedList',
          '|',
          'justifyLeft',
          'justifyRight',
          'justifyCenter',
          'justifyJustify',
          '|',
          'insertTable',
          'codeBlock',
          'divider',
          '|',
          'undo',
          'redo',
        ],
      },
      editorConfig: {
        placeholder: '请输入文本内容...',
        MENU_CONF: {
          // 禁用上传功能
          uploadImage: {
            server: '',
          },
          uploadVideo: {
            server: '',
          },
        },
      },
      mode: 'default', // or 'simple'
      // 预览相关数据
      imagePreviewVisible: false,
      videoPreviewVisible: false,
      currentImageIndex: 0,
      currentVideoIndex: 0,
      currentPreviewImage: '',
      currentPreviewVideo: '',
      currentPreviewTitle: '',
      // 上传loading状态
      imageUploading: false,
      videoUploading: false,
    };
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          // this.initFormData();
          // 当抽屉打开时，调用接口获取文章内容
          this.fetchArticleContent();
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleClose() {
      // 重置表单数据到初始状态
      this.formData = {
        id: null,
        name: '',
        author: '',
        banner: [],
        video: [],
        rawHtml: '<p>请输入文本内容...</p>',
      };

      // 重置loading状态
      this.imageUploading = false;
      this.videoUploading = false;

      // 重置表单验证状态
      if (this.$refs.contentForm) {
        this.$refs.contentForm.clearValidate();
      }

      this.$emit('update:visible', false);
    },
		drawerTitle() {
      return this.nodeData?.name ? `编辑内容 - ${this.nodeData.name}` : '编辑内容';
    },
		drawerFooter() {
			return this.$createElement('div', {
				style: {
					display: 'flex',
					justifyContent: 'flex-end',
					gap: '12px'
				}
			}, [
				this.$createElement('t-button', {
					props: {
						variant: 'outline',
						theme: 'default'
					},
					on: {
						click: this.handleCancel
					}
				}, '取消'),
				this.$createElement('t-button', {
					props: {
						theme: 'primary'
					},
					on: {
						click: this.handleConfirm
					}
				}, '确定')
			]);
		},
		handleCancel() {
			this.handleClose();
		},
		async handleConfirm() {
			try {
        // 验证表单
        const valid = await this.$refs.contentForm.validate();

				if (valid !== true) {
					return;
				}

				const params = {
					...this.formData,
					categoryId: this.categoryId,
					code: this.nodeData?.code,
					banner: this.formData.banner.join(','),
					video: this.formData.video.join(','),
				}

        // 根据是否有id决定调用创建还是更新接口
        if (this.formData.id) {
          // 有id，调用更新接口
          await updateCatalogContent(this.formData.id, params);
          this.$message.success('更新成功');
        } else {
          // 无id，调用创建接口
          await createCatalogContent(params);
          this.$message.success('创建成功');
        }

        this.$emit('success', this.formData);
        this.handleClose();
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error(this.formData.id ? '更新失败，请重试' : '创建失败，请重试');
      }
		},

    // 初始化表单数据
    initFormData() {
      if (this.nodeData) {
        this.formData = {
          id: this.nodeData.id || null,
          name: this.nodeData.name || '',
          author: this.nodeData.author || '',
          banner: this.nodeData.banner || [],
          video: this.nodeData.video || [],
          rawHtml: this.nodeData.rawHtml,
        };
      }
    },

    // 编辑器创建完成回调
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },

    // 图片上传进度回调
    handleImageProgress(percent, file) {
      console.log('图片上传进度:', percent, file);
      this.imageUploading = true;
    },

    // 视频上传进度回调
    handleVideoProgress(percent, file) {
      console.log('视频上传进度:', percent, file);
      this.videoUploading = true;
    },

    // 图片上传成功回调
    handleImageSuccess(response, file) {
      console.log('图片上传成功:', response, file);
      this.imageUploading = false;
      // 直接将链接追加到banner数组中
      const url = response.response?.url ?? '';
      if (url) {
        this.formData.banner = [...this.formData.banner, url];
        this.$message.success('图片上传成功');
      }
    },

    // 视频上传成功回调
    handleVideoSuccess(response, file) {
      console.log('视频上传成功:', response, file);
      this.videoUploading = false;
      // 直接将链接追加到video数组中
      const url = response.response?.url ?? '';
      if (url) {
        this.formData.video = [...this.formData.video, url];
        this.$message.success('视频上传成功');
      }
    },

    // 上传失败回调
    handleUploadFail(error) {
      console.error('上传失败:', error);
      // 重置loading状态
      this.imageUploading = false;
      this.videoUploading = false;
      this.$message.error('上传失败，请重试');
    },

    // 格式化图片上传响应
    formatImageResponse(response) {
			console.log('图片上传响应:', response);
      // 根据实际接口返回格式调整
      return {
        url: response.data ?? '',
        name: response.data ? response.data.split('/').pop() : '',
      };
    },

    // 格式化视频上传响应
    formatVideoResponse(response) {
      // 根据实际接口返回格式调整
			console.log('视频上传响应:', response);
      return {
        url: response.data ?? '',
        name: response.data ? response.data.split('/').pop() : '',
      };
    },

    // 获取文章内容
    async fetchArticleContent() {
      // 从nodeData中获取code，从props中获取categoryId
      const code = this.nodeData?.code;
      const categoryId = this.categoryId;

      // 检查必要参数是否存在
      if (!code || !categoryId) {
        console.warn('缺少必要参数: code 或 categoryId', { code, categoryId });
        return;
      }

      try {
        const response = await getArticleByContentCode(code, categoryId);
				const res = response?.data;
        if (res?.data) {
          // 更新表单数据
          this.formData = {
            ...this.formData,
            id: res?.data?.id || null,
            name: res?.data?.name || '',
            author: res?.data?.author || '',
            banner: (res?.data?.banner && res?.data?.banner.trim()) ? res?.data?.banner.split(',').filter(url => url.trim()) : [],
            video: (res?.data?.video && res?.data?.video.trim()) ? res?.data?.video.split(',').filter(url => url.trim()) : [],
            rawHtml: res?.data?.rawHtml ?? '',
          };
        }
      } catch (error) {
        console.error('获取文章内容失败:', error);
        this.$message.error('获取文章内容失败，请重试');
      }
    },

    // 获取文件名
    getFileName(url) {
      if (!url) return '未知文件';

      try {
        // 尝试从URL中提取文件名
        const parts = url.split('/');
        let fileName = parts[parts.length - 1];

        // 如果文件名包含查询参数，去除它们
        if (fileName.includes('?')) {
          fileName = fileName.split('?')[0];
        }

        // 如果文件名为空或太短，使用默认名称
        if (!fileName || fileName.length < 3) {
          const isImage = url.toLowerCase().match(/\.(jpg|jpeg|png|gif|webp)$/i);
          const isVideo = url.toLowerCase().match(/\.(mp4|avi|mov|wmv|flv|webm)$/i);

          if (isImage) {
            fileName = '图片文件';
          } else if (isVideo) {
            fileName = '视频文件';
          } else {
            fileName = '文件';
          }
        }

        return fileName;
      } catch (error) {
        console.error('解析文件名失败:', error);
        return '未知文件';
      }
    },

    // 移除文件
    async removeFile(type, index) {
			const confirmDialog = await new Promise((resolve) => {
          const instance = TDialog.confirm({
            header: '确认删除',
            body: '确定要删除这个文件吗？',
            confirmBtn: {
              content: '确定删除',
              theme: 'danger',
              loading: false
            },
            cancelBtn: '取消',
            onConfirm: () => {
              resolve(instance);
            },
            onCancel: () => {
              resolve(null);
            },
          });
        });

				if (type === 'banner') {
            this.formData.banner = this.formData.banner.filter((_, i) => i !== index);
            this.$message.success('图片已删除');
          } else if (type === 'video') {
            this.formData.video = this.formData.video.filter((_, i) => i !== index);
            this.$message.success('视频已删除');
          }

					confirmDialog.hide();
    },

    // 预览图片 - 在新标签页中打开
    previewImage(url) {
      if (!url) {
        this.$message.warning('图片链接无效');
        return;
      }

      try {
        // 在新标签页中打开图片
        window.open(url, '_blank');
      } catch (error) {
        console.error('打开图片失败:', error);
        this.$message.error('打开图片失败');
      }
    },

    // 播放视频 - 在新标签页中打开
    playVideo(url) {
      if (!url) {
        this.$message.warning('视频链接无效');
        return;
      }

      try {
        // 在新标签页中打开视频
        window.open(url, '_blank');
      } catch (error) {
        console.error('打开视频失败:', error);
        this.$message.error('打开视频失败');
      }
    },
  },

  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
});
</script>

<style lang="less" scoped>
.content-drawer-body {
  padding: 20px;
  height: 100%;
  overflow-y: auto;

  .content-form {
    // 确保表单项纵向布局
    /deep/ .t-form-item {
      display: flex;
      flex-direction: column;
      width: 100%;

      .t-form-item__content {
        display: flex;
        flex-direction: column;
        width: 100%;
      }
    }

    /deep/ .t-upload__dragger {
      width: 100% !important;
      display: flex;
      flex-direction: column;
    }

    // 确保上传组件整体纵向布局
    /deep/ .t-upload {
      display: flex;
      flex-direction: column;
      width: 100%;
    }

    // 拖拽区域样式
    .upload-drag-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px 20px;
      text-align: center;
      transition: all 0.3s ease;

      &.uploading {
        background-color: #f0f8ff;
        border-color: #1890ff;
      }

      .upload-text {
        margin-top: 12px;
        width: 100%;

        p {
          margin: 8px 0;

          &.upload-tips {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }

    // 上传进度提示样式
    .upload-progress-tip {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 12px 16px;
      background-color: #f0f8ff;
      border: 1px solid #d6e4ff;
      border-radius: 6px;
      margin-bottom: 8px;
      color: #1890ff;
      font-size: 14px;

      .loading-icon {
        margin-right: 8px;
        animation: spin 1s linear infinite;
      }
    }

    @keyframes spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }

    // 文件列表头部样式
    .file-list-header {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-top: 8px;
      margin-bottom: 4px;
      width: 100%;

      .file-count {
        font-size: 12px;
        color: #666;
        font-weight: 500;
      }
    }

    // 文件列表容器 - 纵向布局
    .file-list-container {
      border: 1px solid #e7e7e7;
      border-radius: 6px;
      max-height: 200px;
      overflow-y: auto;
      background-color: #fafafa;
      margin-top: 4px;
      width: 100%;
      display: flex;
      flex-direction: column;
			gap: 4px;

      .file-item {
        display: flex;
        align-items: center;
        height: 60px;
        padding: 8px 12px;
        border-bottom: 1px solid #f0f0f0;
        transition: background-color 0.2s;
        position: relative;
        width: 100%;
        box-sizing: border-box;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          background-color: #f5f5f5;
        }

        .file-preview {
          width: 44px;
          height: 44px;
          margin-right: 12px;
          border-radius: 4px;
          overflow: hidden;
          cursor: pointer;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #f8f8f8;
          border: 1px solid #e0e0e0;
          transition: all 0.2s;

          &:hover {
            border-color: #1890ff;
            box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
          }

          .preview-thumbnail {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 3px;
          }

          .video-thumbnail {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #666;
            position: relative;

            .play-icon {
              position: absolute;
              bottom: 2px;
              right: 2px;
              font-size: 10px;
              color: #1890ff;
            }
          }
        }

        .file-info {
          flex: 1;
          display: flex;
          align-items: center;
          min-width: 0;

          .file-icon {
            margin-right: 8px;
            color: #1890ff;
            flex-shrink: 0;
            font-size: 16px;
          }

          .file-name {
            font-size: 14px;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            line-height: 1.4;
          }
        }

        .file-actions {
          display: flex;
          align-items: center;
          gap: 4px;
          flex-shrink: 0;

          .t-button {
            opacity: 0.7;
            transition: opacity 0.2s;

            &:hover {
              opacity: 1;
            }
          }
        }
      }

      // 当列表为空时的样式
      &:empty {
        display: none;
      }
    }

    .rich-editor-wrapper {
      border: 1px solid #d9d9d9;
      border-radius: 6px;
      overflow: hidden;

      :deep(.w-e-toolbar) {
        border-bottom: 1px solid #d9d9d9;
      }

      :deep(.w-e-text-container) {
        min-height: 500px !important;
        max-height: 600px !important;
        overflow-y: auto;
      }

      :deep(.w-e-text-placeholder) {
        top: 10px;
        left: 10px;
      }
    }
  }
}

// 预览弹窗样式
.image-preview-container,
.video-preview-container {
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e7e7e7;

    .preview-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .preview-controls {
      display: flex;
      align-items: center;
      gap: 12px;

      .preview-counter {
        font-size: 14px;
        color: #666;
        padding: 0 8px;
      }
    }
  }

  .preview-content {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background-color: #f8f8f8;
    border-radius: 6px;
    overflow: hidden;

    .preview-image {
      max-width: 100%;
      max-height: 70vh;
      object-fit: contain;
      border-radius: 4px;
    }

    .preview-video {
      max-width: 100%;
      max-height: 70vh;
      border-radius: 4px;
    }
  }
}

// 弹窗样式覆盖
:deep(.t-dialog__body) {
  padding: 20px;
}

:deep(.t-dialog__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #e7e7e7;
}
</style>